package client_commands;

import java.util.StringTokenizer;

import client.ClientApplication;
import client.ClientBindObject;
import client_tree.User;

public class SERV_BLOCKCommand extends Command {

	public SERV_BLOCKCommand(String parameter) {
		setCode(SERV_BLOCK);
		setParameter(parameter);
	}
	
	
	@Override
	public boolean executeCommand(ClientApplication theApp) {
		StringTokenizer tokens = new StringTokenizer(getParameter());
		
		String username = tokens.nextToken();

		User user = theApp.getClientModel().getOnlineModel().getUserByUsername(username);;

		if (user == null) {
			user = theApp.getClientModel().getOfflineModel().getUserByUsername(username);;
		}
		
		if (user == null) {
			return false;
		}
		
		user.setStatus(OFFLINE_STATUS);
		theApp.getClientModel().addUser(user);
		
		
		if ( ClientApplication.clientBinding.get(username) != null ) {
			
			ClientBindObject cbo = ClientApplication.clientBinding.get(username);
			if (cbo.getDialog() != null) {
				cbo.getDialog().setConnection(null);
				cbo.getDialog().setSendButtonRights(false);
			}
			
			cbo.getConnection().writeData( Long.toString(cbo.getConnection().getConnectionID()) );
			
			try {
				Thread.sleep(1000);
			}
			catch (InterruptedException ie) {
				ie.printStackTrace();
			}
			
			cbo.getConnection().quitConnection();
			cbo.setConnection(null);
		}

		
		return true;
	}
}
